#include "stm32f4xx.h"                  // Device header

void MyRTC_Init(void)
{
		RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);	// PWR区
		PWR_BackupAccessCmd(ENABLE); // 允许访问BKP
	
	if(RTC_ReadBackupRegister(RTC_BKP_DR0)!=0x1145){
		RCC_LSEConfig(RCC_LSE_ON); // LSE起振
		while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) != SET); // 等待LSE
		RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE); // LSE_SEL
		RCC_RTCCLKCmd(ENABLE); // RTC_CLK 启动
	
		RTC_InitTypeDef RTC_InitStruct;
		RTC_InitStruct.RTC_AsynchPrediv = 128-1;
		RTC_InitStruct.RTC_SynchPrediv = 256-1;
		RTC_InitStruct.RTC_HourFormat=RTC_HourFormat_24;
		RTC_Init(&RTC_InitStruct);
		
		//MyRTC_SetTime();
		RTC_DateTypeDef RTC_DateStruct;
		RTC_DateStruct.RTC_Date = 7;
		RTC_DateStruct.RTC_Month = 7;
		RTC_DateStruct.RTC_WeekDay = RTC_Weekday_Friday;
		RTC_DateStruct.RTC_Year = 24;
		RTC_SetDate(RTC_Format_BIN,&RTC_DateStruct);
	
		RTC_TimeTypeDef RTC_TimeStruct;
		RTC_TimeStruct.RTC_H12 = RTC_H12_PM;
		RTC_TimeStruct.RTC_Hours = 23;
		RTC_TimeStruct.RTC_Minutes = 57;
		RTC_TimeStruct.RTC_Seconds = 24;
		RTC_SetTime(RTC_Format_BIN,&RTC_TimeStruct);
		
		RTC_WriteBackupRegister(RTC_BKP_DR0,0x1145);
	}
}

//如果LSE无法起振导致程序卡死在初始化函数中
//可将初始化函数替换为下述代码，使用LSI当作RTCCLK
//LSI无法由备用电源供电，故主电源掉电时，RTC走时会暂停
/* 
void MyRTC_Init(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP, ENABLE);
	
	PWR_BackupAccessCmd(ENABLE);
	
	if (BKP_ReadBackupRegister(BKP_DR1) != 0xA5A5)
	{
		RCC_LSICmd(ENABLE);
		while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) != SET);
		
		RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI);
		RCC_RTCCLKCmd(ENABLE);
		
		RTC_WaitForSynchro();
		RTC_WaitForLastTask();
		
		RTC_SetPrescaler(40000 - 1);
		RTC_WaitForLastTask();
		
		MyRTC_SetTime();
		
		BKP_WriteBackupRegister(BKP_DR1, 0xA5A5);
	}
	else
	{
		RCC_LSICmd(ENABLE);
		while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) != SET);
		
		RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI);
		RCC_RTCCLKCmd(ENABLE);
		
		RTC_WaitForSynchro();
		RTC_WaitForLastTask();
	}
}*/
/*
void MyRTC_SetTime(void)
{
	time_t time_cnt;
	struct tm time_date;
	
	time_date.tm_year = MyRTC_Time[0] - 1900;
	time_date.tm_mon = MyRTC_Time[1] - 1;
	time_date.tm_mday = MyRTC_Time[2];
	time_date.tm_hour = MyRTC_Time[3];
	time_date.tm_min = MyRTC_Time[4];
	time_date.tm_sec = MyRTC_Time[5];
	
	time_cnt = mktime(&time_date) - 8 * 60 * 60;
	
	RTC_SetCounter(time_cnt);
	RTC_WaitForLastTask();
}

void MyRTC_ReadTime(void)
{
	time_t time_cnt;
	struct tm time_date;
	
	time_cnt = RTC_GetCounter() + 8 * 60 * 60;
	
	time_date = *localtime(&time_cnt);
	
	MyRTC_Time[0] = time_date.tm_year + 1900;
	MyRTC_Time[1] = time_date.tm_mon + 1;
	MyRTC_Time[2] = time_date.tm_mday;
	MyRTC_Time[3] = time_date.tm_hour;
	MyRTC_Time[4] = time_date.tm_min;
	MyRTC_Time[5] = time_date.tm_sec;
}*/
